import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Table,
  Modal,
  Form,
  Input,
  Button,
  Row,
  Col,
  Divider,
  Select,
  TreeSelect,
  message,
  Radio,
  Tag,
} from 'antd';

import { isNumAndLetter } from '../../utils/utils';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './EmployeeManagement.less';

const FormItem = Form.Item;
const { Option, OptGroup } = Select;
const TreeNode = TreeSelect.TreeNode;
const RadioGroup = Radio.Group;

@connect(({ system, role }) => ({
  system,
  role,
}))
@Form.create()
export default class EmployeeManagement extends PureComponent {
  state = {
    modalVisible: false,
    isEdit: false,
    treeSelelctValue: -1,
    passwordShiow: false,
    branchIdList: [],
    passwordSelect: '',
    roleListValue: [],
    userDetails: {},
    value: undefined,
    userId: '',
    searchFilters: {
      name: '',
      employeeNum: '',
      phone: '',
    },
    employeeUserName: null,
    employeePassword: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'system/fetchUsers',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
    dispatch({
      type: 'system/fetchBasic',
    });
    dispatch({
      type: 'system/getBranchTreeList',
    });
    dispatch({
      type: 'role/getRoleListByCreateUser',
    });
  }

  handleSearchNameChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        name: e.target.value,
      },
    });
  };

  handleSearchEmplyeNumChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        employeeNum: e.target.value,
      },
    });
  };

  handleSearchPhoenChange = e => {
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        phone: e.target.value,
      },
    });
  };

  handleSearch = e => {
    this.props.dispatch({
      type: 'system/fetchUsers',
      payload: {
        offset: 0,
        limit: 10,
        name: this.state.searchFilters.name,
        employeeNum: this.state.searchFilters.employeeNum,
        phone: this.state.searchFilters.phone,
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      searchFilters: {
        ...this.state.searchFilters,
        name: '',
        employeeNum: '',
        phone: '',
      },
    });
    dispatch({
      type: 'system/fetchUsers',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  };

  renderSimpleForm() {
    // const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="员工姓名">
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.name}
                onChange={this.handleSearchNameChange}
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="工号">
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.employeeNum}
                onChange={this.handleSearchEmplyeNumChange}
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="电话号码">
              <Input
                placeholder="请输入"
                value={this.state.searchFilters.phone}
                onChange={this.handleSearchPhoenChange}
              />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handleAddUsers}>
                新增
              </Button>
            </div>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.handleSearch}>
                查询
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleAddEmployeeOnOK = () => {
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // console.log("value", values)
        if (this.state.isEdit && this.state.employeePassword.length < 6) {
          message.error('密码不能低于6位');
          return;
        }
        this.props.dispatch({
          type: 'system/existUserName',
          payload: {
            userName: this.state.employeeUserName,
          },
          callback: () => {
            const { system: { userNameResult } } = this.props;
            if (userNameResult.code == 200) {
              if (this.state.isEdit) {
                this.props.form.resetFields();
                this.props.dispatch({
                  type: 'system/addUsers',
                  payload: {
                    ...values,
                    userName: this.state.employeeUserName,
                    password: this.state.employeePassword,
                  },
                  callback: () => {
                    this.props.dispatch({
                      type: 'system/fetchUsers',
                      payload: {
                        offset: 0,
                        limit: 10,
                      },
                    });
                    this.setState({
                      employeeUserName: null,
                      employeePassword: null,
                    });
                  },
                });
              } else {
                this.props.form.resetFields();
                this.props.dispatch({
                  type: 'system/updataUsers',
                  payload: {
                    id: this.state.userId,
                    ...values,
                    userName: this.state.employeeUserName,
                    // password: this.state.employeePassword,
                    state: values.state,
                  },
                  callback: () => {
                    this.props.dispatch({
                      type: 'system/fetchUsers',
                      payload: {
                        offset: 0,
                        limit: 10,
                      },
                    });
                  },
                });
              }
              this.setState({ modalVisible: false });
            } else {
              message.error('用户名已存在');
            }
          },
        });
      }
    });
  };

  handleOnCancel = () => {
    this.props.form.resetFields();
    this.setState({
      modalVisible: false,
    });
  };

  handleAddUsers = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'system/getBranchTreeList',
    });
    this.setState({
      modalVisible: true,
      isEdit: true,
    });
  };

  edit = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'system/getBranchTreeList',
    });
    dispatch({
      type: 'system/userDetailsShow',
      payload: {
        id: record.id,
      },
      callback: () => {
        const { system: { userDetails } } = this.props;
        // console.log("userDetails", userDetails)
        this.setState({
          userDetails,
          userId: record.id,
          modalVisible: true,
          passwordShiow: true,
          isEdit: false,
        });
      },
    });
  };

  handleAccountIsAvailable = value => {
    this.setState({
      passwordSelect: value,
    });
  };

  // //密码重置
  handleChangePassword = record => {
    // console.log("AADAFAFArecord")
    // console.log(record.id)
    this.props.dispatch({
      type: 'users/changePassword',
      payload: {
        userId: record.id,
      },
      callback: () => {
        this.props.dispatch({
          type: 'system/fetchUsers',
          payload: {
            offset: 0,
            limit: 10,
          },
        });
      },
    });
  };

  renderOption = data => {
    // console.log("data", data)
    const options = [];
    data.map(item => {
      options.push(
        <Option key={item.id} value={item.id} disabled={item.valid == 1 ? false : true}>
          {item.roleName}
        </Option>
      );
    });
    return options;
  };

  handleBranchIdList = value => {
    this.setState({
      branchIdList: value,
    });
  };

  renderTreeNodesChildren = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode value={item.id} title={item.orgName} key={item.id} dataRef={item}>
            {this.renderTreeNodesChildren(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.id} key={item.id} dataRef={item} title={item.orgName} />;
    });
  };

  handleRoleListChange = value => {
    this.setState({
      roleListValue: value,
    });
  };

  columns = [
    {
      title: '工号',
      dataIndex: 'employeeNum',
      key: 'employeeNum',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '电话号码',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '所属组织',
      dataIndex: 'orgName',
      key: 'orgName',
    },
    {
      title: '角色',
      dataIndex: `roleNameList`,
      key: 'roleNameList',
      width: '20%',
      render: (text, record) =>
        record.roleNameList.map((item, index) => {
          return (
            <Tag key={index} color="green">
              {item}
            </Tag>
          );
        }),
    },
    {
      title: '操作',
      dataIndex: 'state',
      key: 'id',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.edit(record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleChangePassword(record)}>密码重置</a>
        </Fragment>
      ),
    },
  ];

  handleEmployeeUserName = () => {
    if (this.state.isEdit) {
      return this.state.employeeUserName;
    } else {
      return this.state.userDetails.userName;
    }
  };

  handleEmployeeUserNameChangel = e => {
    let value = isNumAndLetter(e.target.value);
    this.setState({
      employeeUserName: value,
    });
  };

  handleEmployeePassword = () => {
    if (this.state.isEdit) {
      return this.state.employeePassword;
    } else {
      return this.state.userDetails.password;
    }
  };

  handleEmployeePasswordChangel = e => {
    this.setState({
      employeePassword: e.target.value,
    });
  };

  handleStandardTableChange = e => {
    // console.log('handleStandardTableChange', e);
    this.props.dispatch({
      type: 'system/fetchUsers',
      payload: {
        offset: (e.current - 1) * e.pageSize,
        limit: e.pageSize,
        name: this.state.searchFilters.name,
        employeeNum: this.state.searchFilters.employeeNum,
        phone: this.state.searchFilters.phone,
      },
    });
    // this.props.dispatch({
    //   type: 'system/fetchUsers',
    //   payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
    // });
  };

  handleBlurPassword = e => {
    if (e.target.value.length < 6) {
      message.error('密码不能低于6位');
    }
  };

  handleBlurUserName = e => {
    this.props.dispatch({
      type: 'system/existUserName',
      payload: {
        userName: e.target.value,
      },
      callback: () => {
        const { system: { userNameResult } } = this.props;
        if (userNameResult.code != 200) {
          message.error('用户名已存在');
        }
      },
    });
  };

  render() {
    const { system: { userList, userLoading, userPage, allBranchTreeList } } = this.props;
    const { role: { roleListByUser } } = this.props;
    const { modalVisible, isEdit } = this.state;
    const { dispatch, form } = this.props;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderLayout title="员工管理">
      {/* {JSON.stringify(this.state.userDetails)} */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <Table
              columns={this.columns}
              dataSource={userList}
              rowKey="id"
              pagination={userPage}
              loading={userLoading}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title={isEdit ? '新增员工' : '员工信息'}
          visible={this.state.modalVisible}
          onCancel={this.handleOnCancel}
          onOk={this.handleAddEmployeeOnOK}
          confirmLoading={userLoading}
        >
          <Form>
            <FormItem {...formItemLayout} label="登录账号">
              {/* {getFieldDecorator('userName', {
                  rules:
                  [{  pattern: /[^a-zA-Z0-9._]/g, message: '账号只能是数字或字母' }],
                })()} */}

              <Input
                placeholder="请输入登录账号"
                value={this.handleEmployeeUserName()}
                onBlur={this.handleBlurUserName}
                onChange={this.handleEmployeeUserNameChangel}
                style={{ width: '100%' }}
                disabled={!this.state.isEdit}
                autoComplete="off"
              />
            </FormItem>
            {isEdit == true ? (
              <FormItem {...formItemLayout} label="初始密码">
                {/* {getFieldDecorator('password', {
                  rules:
                  [{  min: 6, message: '密码长度必须大于6位！' }],
                })()} */}
                <Input
                  placeholder="请输入初始密码"
                  type="password"
                  onBlur={this.handleBlurPassword}
                  value={this.handleEmployeePassword()}
                  onChange={this.handleEmployeePasswordChangel}
                  autoComplete="off"
                />
              </FormItem>
            ) : null}
            <FormItem {...formItemLayout} label="员工工号">
              {form.getFieldDecorator('employeeNum', {
                initialValue: isEdit ? null : this.state.userDetails.employeeNum,
              })(<Input placeholder="请输入员工工号" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="员工姓名">
              {form.getFieldDecorator('name', {
                initialValue: isEdit ? null : this.state.userDetails.name,
              })(<Input placeholder="请输入员工姓名" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="联系方式">
              {form.getFieldDecorator('phone', {
                initialValue: isEdit ? null : this.state.userDetails.phone,
                rules: [
                  { max: 11, message: '联系方式应该为11位' },
                  { min: 11, message: '联系方式应该为11位' },
                ],
              })(<Input placeholder="请输入联系方式" />)}
            </FormItem>
            {allBranchTreeList && (
              <FormItem {...formItemLayout} label="所属组织">
                {getFieldDecorator('branchId', {
                  initialValue: isEdit ? null : this.state.userDetails.branchId,
                })(
                  <TreeSelect
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder="请选择"
                    allowClear
                    treeDefaultExpandAll
                    onChange={this.handleBranchIdList}
                  >
                    {allBranchTreeList && this.renderTreeNodesChildren(allBranchTreeList)}
                  </TreeSelect>
                )}
              </FormItem>
            )}

            <FormItem {...formItemLayout} label="角色">
              {getFieldDecorator('roleIdList', {
                initialValue: isEdit ? [] : this.state.userDetails.roleIdList,
              })(
                <Select
                  mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onChange={this.handleRoleListChange}
                  onSelect={this.handleSelectRoleList}
                >
                  {roleListByUser && this.renderOption(roleListByUser)}
                </Select>
              )}
            </FormItem>

            {this.state.passwordShiow ? (
              <FormItem {...formItemLayout} label="是否可用">
                {form.getFieldDecorator('state', {
                  initialValue: isEdit ? null : this.state.userDetails.state,
                })(
                  <RadioGroup onChange={this.handleAccountIsAvailable}>
                    <Radio value={1}>是</Radio>
                    <Radio value={0}>否</Radio>
                  </RadioGroup>
                )}
              </FormItem>
            ) : null}
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
